<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="考勤月份" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="请选择考勤月份"
            :disabled-date="disabledDate"
            @change="changeMonth"
          />
        </el-form-item>
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入关键字"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-form-item>
        <el-button type="primary" :loading="download_loading" @click="download()"><i-ep-download />导出</el-button>
        <el-text type="danger" style="margin-left: 20px">统计截止时间为昨天</el-text>
      </el-form-item>
      <el-table
        v-loading="loading"
        :data="CheckInDetailPersonListForm"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" type="index" min-width="60" align="center"></el-table-column>
        <el-table-column key="personName" label="人员姓名" min-width="80" align="center" prop="personName" />
        <el-table-column
          v-if="loginRole === 'SysUser'"
          key="projectName"
          label="所属项目"
          align="center"
          min-width="300"
          prop="projectName"
        />
        <el-table-column
          v-if="loginRole != 'Corp'"
          key="corpName"
          label="所属公司"
          align="center"
          min-width="300"
          prop="corpName"
        />
        <el-table-column
          v-if="loginRole != 'Corp'"
          key="corpTypeName"
          label="公司类型"
          align="center"
          min-width="100"
          prop="corpTypeName"
        />
        <el-table-column key="groupName" label="班组" align="center" min-width="100" prop="groupName" />
        <el-table-column key="workTypeName" label="工种" align="center" min-width="100" prop="workTypeName" />
        <el-table-column
          key="monthCheckinAddDay"
          label="本月应考勤天数"
          min-width="120"
          align="center"
          prop="monthCheckinAddDay"
        />
        <el-table-column
          key="monthCheckinDay"
          label="本月实际出勤天数"
          min-width="130"
          align="center"
          prop="monthCheckinDay"
        />
        <el-table-column key="absenceDay" label="缺勤天数" align="center" min-width="80" prop="absenceDay" />
        <el-table-column key="presenceRate" label="到岗率" align="center" min-width="80" prop="presenceRate">
          <template #default="scope">{{ scope.row.presenceRate }}% </template>
        </el-table-column>
        <el-table-column key="absenceRate" label="缺勤率" align="center" min-width="80" prop="absenceRate">
          <template #default="scope">{{ scope.row.absenceRate }}% </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="80">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="openDialog(scope.row)">
              <i-ep-grid />
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageIndex"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialogAddOrEdit.visible"
      :fullscreen="mobile === 'mobile'"
      class="system"
      style="width: 550px"
      :title="dialogAddOrEdit.title"
      append-to-body
      draggable
      close-icon="CloseBold"
    >
      <el-descriptions v-loading="loading" class="margin-top" column="2" border style="width: 490px; margin: auto">
        <el-descriptions-item label-align="right">
          <template #label>
            <div class="cell-item">姓名</div>
          </template>
          {{ CheckInDetailPersonForm?.personName }}
        </el-descriptions-item>
        <el-descriptions-item label-align="right">
          <template #label>
            <div class="cell-item">所属公司名称</div>
          </template>
          {{ CheckInDetailPersonForm?.corpName }}
        </el-descriptions-item>
        <el-descriptions-item label-align="right">
          <template #label>
            <div class="cell-item">所属公司类型</div>
          </template>
          {{ CheckInDetailPersonForm?.corpTypeName }}
        </el-descriptions-item>
        <el-descriptions-item label-align="right">
          <template #label>
            <div class="cell-item">班组名称</div>
          </template>
          {{ CheckInDetailPersonForm?.groupName }}
        </el-descriptions-item>
        <el-descriptions-item label-align="right">
          <template #label>
            <div class="cell-item">工种</div>
          </template>
          {{ CheckInDetailPersonForm?.workTypeName }}
        </el-descriptions-item>
        <!-- <el-descriptions-item label-align="right">
                    <template #label>
                        <div class="cell-item">
                            进场时间
                        </div>
                    </template>
                    2023-10-01
                </el-descriptions-item>
                <el-descriptions-item label-align="right">
                    <template #label>
                        <div class="cell-item">
                            离场时间
                        </div>
                    </template>
                    2023-12-20
                </el-descriptions-item> -->
        <el-descriptions-item label-align="right">
          <template #label>
            <div class="cell-item">考勤月份</div>
          </template>
          {{ queryParams.month }}
        </el-descriptions-item>
      </el-descriptions>

      <table class="table">
        <tr style="margin: auto; line-height: 30px; background: #e5eafa 100%">
          <td>日期</td>
          <td v-for="(item, index) in currentTds[0]" :key="index">{{ item }}日</td>
        </tr>
        <tr style="background: #ffffff; background-color: rgba(255, 255, 255, 1); line-height: 30px">
          <td>出勤</td>
          <td v-for="(item, index) in currentTds[0]" :key="index">
            <template v-if="checkindays.includes(item)"> √ </template>
            <template v-else></template>
          </td>
        </tr>
        <tr style="margin: auto; line-height: 30px; background: #e5eafa 100%">
          <td>日期</td>
          <td v-for="(item, index) in currentTds[0]" :key="index">{{ item + 8 }}日</td>
        </tr>
        <tr style="background: #ffffff; background-color: rgba(255, 255, 255, 1); line-height: 30px">
          <td>出勤</td>
          <td v-for="(item, index) in currentTds[0]" :key="index">
            <template v-if="checkindays.includes(item + 8)"> √ </template>
            <template v-else></template>
          </td>
        </tr>
        <tr style="margin: auto; line-height: 30px; background: #e5eafa 100%">
          <td>日期</td>
          <td v-for="(item, index) in currentTds[0]" :key="index">{{ item + 16 }}日</td>
        </tr>
        <tr style="background: #ffffff; background-color: rgba(255, 255, 255, 1); line-height: 30px">
          <td>出勤</td>
          <td v-for="(item, index) in currentTds[0]" :key="index">
            <template v-if="checkindays.includes(item + 16)"> √ </template>
            <template v-else></template>
          </td>
        </tr>
        <tr style="margin: auto; line-height: 30px; background: #e5eafa 100%">
          <td>日期</td>
          <td v-for="(item, index) in currentTds[1]" :key="index">{{ item + 24 }}日</td>
        </tr>
        <tr style="background: #ffffff; background-color: rgba(255, 255, 255, 1); line-height: 30px">
          <td>出勤</td>
          <td v-for="(item, index) in currentTds[1]" :key="index">
            <template v-if="checkindays.includes(item + 24)"> √ </template>
            <template v-else></template>
          </td>
        </tr>
      </table>

      <!-- <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit">确 定</el-button>
                    <el-button @click="closeDialog()">取 消</el-button>
                </div>
            </template> -->
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import moment from "moment";
import { getDicts } from "@/store/modules/dict";
import { CheckInDetailPersonListForm, ParamsType } from "@/api/checkin/types";
import { getPersonCheckinMonth, getCheckInDetailPersonForm, exportDetailMonth } from "@/api/checkin/index";
import { useScreen } from "@/store/modules/screen";
import { downloadFile } from "@/utils";
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);

const loginRole = ref(localStorage.getItem("usertypeName"));

const total = ref(0);
const loading = ref(false);
const queryFormRef = ref(ElForm);
const CheckInDetailPersonListForm = ref<CheckInDetailPersonListForm[]>();
const CheckInDetailPersonForm = ref<CheckInDetailPersonListForm>();
const queryParams = reactive<ParamsType>({
  pageIndex: 1,
  pageSize: 20,
  month: new Date().toISOString().substr(0, 7), // 当前年月
});
const dialogAddOrEdit = reactive<DialogOption>({
  id: 0,
  visible: false,
  title: "详情",
});

const dialogInOrOut = reactive({
  id: 0,
  ids: [],
  visible: false,
  title: "",
  label: "",
});

const download_loading = ref(false);

function download() {
  download_loading.value = true;
   let params = {};
  Object.assign(params, queryParams);
  params.month = queryParams.month.replaceAll("-", "");
  exportDetailMonth(params).then((response: any) => {
    if (!response.headers["content-disposition"]) {
      const decoder = new TextDecoder("utf-8");
      const resp = decoder.decode(response.data);
      let objResp = JSON.parse(resp);
      ElMessage.error(objResp.msg);
      download_loading.value = false;
      return;
    }

    downloadFile(response);
    download_loading.value = false;
  });
}

/**
 * 禁用日期
 */
const disabledDate = (time: Date) => {
  return time.getTime() > moment().toDate().getTime();
};

/* 列表查询 */
async function handleQuery() {
  loading.value = true;
  let submitForm = {};
  Object.assign(submitForm, queryParams);
  submitForm.month = queryParams.month.replaceAll("-", "");
  let list = await getPersonCheckinMonth(submitForm);
  if (list.type === 0) {
    if (list.success) {
      CheckInDetailPersonListForm.value = list.data.list;

      queryParams.pageIndex = list.data.pageNum;
      queryParams.pageSize = list.data.pageSize;
      total.value = list.data.total;
    } else {
      ElMessage.error(list.msg);
    }
  } else {
    ElMessage.error(list.msg);
  }
  loading.value = false;
}

function changeMonth(val: string) {
  if (val === null) queryParams.month = "";
  else queryParams.month = moment(val).format("YYYY-MM");
}
/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageIndex = 1;
  queryParams.pageSize = 20;
  handleQuery();
}
const currentMonthDays = ref(10);
const currentTds = ref<Array<any>>([]);
const checkindays = ref<Array<any>>([]);
/* 新增/编辑 */
function openDialog(row: CheckInDetailPersonListForm) {
  CheckInDetailPersonForm.value = row;
  dialogAddOrEdit.visible = true;
  dialogAddOrEdit.title = "查看详情";

  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 注意：月份是从0开始的，所以要加1
  currentMonthDays.value = new Date(year, month, 0).getDate();
  currentTds.value[0] = 8;
  currentTds.value[1] = currentMonthDays.value - 24;

  getCheckInDetailPersonForm(row.memberId, queryParams.month?.replaceAll("-", "")).then((res) => {
    if (res.success === true) {
      checkindays.value = res.data;
    }
    // console.log(checkindays.value);
  });
}

let selectMemberIds = [];
let selectRow = [];
const handleSelectionChange = (selection: any) => {
  selectMemberIds = [];
  selectRow = [];
  selection.map((item: any) => {
    selectMemberIds.push(item.groupId);
    selectRow.push(item);
  });
};

onMounted(() => {
  handleQuery();
});
</script>

<style lang="less" scoped>
:deep(.addform .el-dialog__body) {
  height: var(--mobileAddFormHeight);
  overflow-y: auto;
}

td {
  text-align: center;
  font-size: 14px;
  text-align: center;
  font-family: Microsoft Yahei;
  font-family: Roboto !important;
  border: 1px solid #bbbbbb;
  border-collapse: collapse;
}

.div-title {
  border: 1px solid #bbbbbb;
}

.table {
  border-collapse: collapse;
  border: 0px solid #bbbbbb;
  width: 490px;
  margin: auto;
  margin-top: 10px;
  background: #ffffff;
}
</style>
